package com.lgc.demo.linklist;

public class DeleteLinkNote {
    /**
     * 单链表删数
     *
     * @param args
     */
    public static void main(String[] args) {
        Node node4 = new Node();
        node4.setValue(4);
        node4.setNext(null);

        Node node3 = new Node();
        node3.setValue(3);
        node3.setNext(node4);

        Node node2 = new Node();
        node2.setValue(2);
        node2.setNext(node3);

        Node node1 = new Node();
        node1.setValue(1);
        node1.setNext(node2);

        Node node11 = new Node();
        node11.setValue(3);
        node11.setNext(node1);

        Node node111 = new Node();
        node111.setValue(3);
        node111.setNext(node11);

        Node head = node111;
        writeLink(head);

        head = deleteNode(head, 3);

        System.out.println("--------------------------------------------");

        writeLink(head);

        int a = 0;
    }

    private static void writeLink(Node head) {
        while (head != null) {
            System.out.println(head.getValue());
            head = head.getNext();
        }
    }

    private static Node deleteNode(Node head, int value) {

        while (head != null && head.getValue() == value) {
            head = head.getNext();
        }

        Node pre = head;

        while (pre != null) {
            Node curr = pre.getNext();
            if (curr != null) {
                if (curr.getValue() == value) {
                    pre.setNext(curr.getNext());
                } else {
                    pre = curr;
                }
            } else {
                break;
            }
        }

        return head;
    }
}
